import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDatailById } from '@/api/user'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, data) {
      state.token = data
      setToken(data)
    },
    getUserInfo(state, data) {
      state.userInfo = data
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(store, data) {
      try {
        const res = await login(data)
        store.commit('setToken', res)
        setTimeStamp()
        console.log('登录成功')
        // if (res.data.success) {
        //   store.commit('setToken', res.data.data)
        // }
      } catch (error) {
        console.log('失败逻辑')
        console.log(error)
      }
    }, logout(store) {
      // 清理 state
      // 1. 清理 token
      store.commit('removeToken')
      // 2. 清理 userInfo
      store.commit('removeUserInfo')
    },
    async getUserInfo(store) {
      const resSimple = await getUserInfo()
      const userId = resSimple.userId
      const resDetail = await getUserDatailById(userId)

      const res = {
        ...resSimple,
        ...resDetail
      }
      store.commit('getUserInfo', res)
      return res
    }
  }
}
